<?php
session_start();
require_once 'app/core/db.php';

// Get user email from session
$user_email = $_SESSION['user_email'] ?? null;

// ===== GET USER_ID FROM EMAIL START =====
$user_id = null;
if ($user_email) {
    try {
        $pdo = getDbConnection();
        $stmt = $pdo->prepare("SELECT id FROM leads WHERE email = ?");
        $stmt->execute([$user_email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $user_id = $user['id'];
            $_SESSION['user_id'] = $user_id;
        } else {
            // User not found, redirect to login
            header('Location: index.php');
            exit;
        }
    } catch (Exception $e) {
        error_log("Error getting user_id: " . $e->getMessage());
        header('Location: index.php');
        exit;
    }
} else {
    // Not logged in, redirect to login
    header('Location: index.php');
    exit;
}
// ===== GET USER_ID FROM EMAIL END =====

// Get saved projects with JOIN
$stmt = $pdo->prepare("
    SELECT 
        p.*,
        usp.saved_at
    FROM user_saved_projects usp
    INNER JOIN projects p ON usp.project_id = p.id
    WHERE usp.user_id = ?
    ORDER BY usp.saved_at DESC
");
$stmt->execute([$user_id]);
$saved_projects = $stmt->fetchAll(PDO::FETCH_ASSOC);

$count = count($saved_projects);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Saved Projects - ClientRadar</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: #f5f7fa;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
        }
        
        .page-header {
            margin-bottom: 40px;
        }
        
        .page-header h1 {
            font-size: 32px;
            margin-bottom: 10px;
            color: #1a1a1a;
        }
        
        .page-header h1 i {
            color: #2196F3;
            margin-right: 10px;
        }
        
        .project-count {
            color: #666;
            font-size: 16px;
        }
        
        .empty-state {
            text-align: center;
            padding: 100px 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .empty-state i {
            font-size: 80px;
            color: #e0e0e0;
            margin-bottom: 20px;
        }
        
        .empty-state h2 {
            font-size: 24px;
            color: #333;
            margin-bottom: 15px;
        }
        
        .empty-state p {
            color: #666;
            margin-bottom: 30px;
            font-size: 16px;
        }
        
        .project-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
        }
        
        .project-card:hover {
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .project-title {
            font-size: 22px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 12px;
            line-height: 1.4;
        }
        
        .project-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 15px;
            font-size: 14px;
            color: #666;
        }
        
        .project-meta span {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .project-meta i {
            color: #2196F3;
        }
        
        .project-description {
            color: #555;
            line-height: 1.7;
            margin-bottom: 20px;
            font-size: 15px;
        }
        
        .project-actions {
            display: flex;
            gap: 12px;
            padding-top: 20px;
            border-top: 1px solid #f0f0f0;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #2196F3;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1976D2;
        }
        
        .btn-danger {
            background: #f44336;
            color: white;
        }
        
        .btn-danger:hover {
            background: #d32f2f;
        }
        
        .btn-outline {
            background: white;
            color: #666;
            border: 1.5px solid #e0e0e0;
        }
        
        .btn-outline:hover {
            background: #f8f9fa;
            border-color: #2196F3;
            color: #2196F3;
        }
        
        .saved-badge {
            display: inline-block;
            padding: 6px 14px;
            background: #e3f2fd;
            color: #1976d2;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
        }
        
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #2196F3;
            text-decoration: none;
            margin-bottom: 30px;
            font-weight: 500;
            font-size: 16px;
        }
        
        .back-link:hover {
            text-decoration: underline;
        }
        
        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 16px;
            padding: 30px;
            max-width: 700px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e5e7eb;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #64748b;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
        }
        
        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .proposal-text {
            background: #f8f9fa;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 20px;
            font-size: 15px;
            line-height: 1.8;
            color: #1e293b;
            white-space: pre-wrap;
            margin-bottom: 20px;
        }
        
        .copy-btn {
            background: #667eea;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .copy-btn:hover {
            background: #5568d3;
        }
        
        .copy-btn.copied {
            background: #10b981;
        }
        
        .error-message {
            background: #fef2f2;
            border: 2px solid #fecaca;
            border-radius: 8px;
            padding: 15px;
            color: #991b1b;
            margin-bottom: 15px;
        }
        
        @media (max-width: 768px) {
            .project-actions {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="ui/projects_table.php" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to Projects
        </a>
        
        <div class="page-header">
            <h1><i class="fas fa-bookmark"></i> My Saved Projects</h1>
            <p class="project-count">You have <?php echo $count; ?> saved project<?php echo $count != 1 ? 's' : ''; ?></p>
        </div>
        
        <?php if (empty($saved_projects)): ?>
            <div class="empty-state">
                <i class="far fa-bookmark"></i>
                <h2>No Saved Projects Yet</h2>
                <p>Start saving projects you're interested in to keep track of them here.</p>
                <a href="ui/projects_table.php" class="btn btn-primary">
                    <i class="fas fa-search"></i> Browse Projects
                </a>
            </div>
        <?php else: ?>
            <?php foreach ($saved_projects as $project): ?>
                <div class="project-card" data-project-id="<?php echo $project['id']; ?>">
                    <h2 class="project-title"><?php echo htmlspecialchars($project['title']); ?></h2>
                    
                    <div class="project-meta">
                        <span class="saved-badge">
                            <i class="fas fa-bookmark"></i>
                            Saved on <?php echo date('M d, Y', strtotime($project['saved_at'])); ?>
                        </span>
                        
                        <?php if (!empty($project['budget'])): ?>
                            <span><i class="fas fa-dollar-sign"></i> <?php echo htmlspecialchars($project['budget']); ?></span>
                        <?php endif; ?>
                        
                        <?php if (!empty($project['created_at'])): ?>
                            <span><i class="far fa-calendar"></i> Posted <?php echo date('M d, Y', strtotime($project['created_at'])); ?></span>
                        <?php endif; ?>
                        
                        <?php if (!empty($project['category'])): ?>
                            <span><i class="fas fa-tag"></i> <?php echo htmlspecialchars($project['category']); ?></span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="project-description">
                        <?php 
                        $description = htmlspecialchars($project['description']);
                        echo strlen($description) > 350 ? substr($description, 0, 350) . '...' : $description;
                        ?>
                    </div>
                    
                    <div class="project-actions">
                        <?php if (!empty($project['project_url'])): ?>
                            <a href="<?php echo htmlspecialchars($project['project_url']); ?>" target="_blank" class="btn btn-primary">
                                <i class="fas fa-external-link-alt"></i> View Original Post
                            </a>
                        <?php endif; ?>
                        
                        <button type="button" class="btn btn-outline" 
                                onclick="generateProposal(<?= $project['id'] ?>, '<?= addslashes(htmlspecialchars($project['title'])) ?>')">
                            <i class="fas fa-file-alt"></i> Generate Proposal
                        </button>
                        
                        <button type="button" class="btn btn-danger btn-unsave" data-project-id="<?php echo $project['id']; ?>">
                            <i class="fas fa-trash-alt"></i> Remove from Saved
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <!-- Proposal Modal -->
    <div id="proposalModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>✨ AI Generated Proposal</h2>
                <button class="modal-close" onclick="closeModal()">×</button>
            </div>
            <div id="modalBody"></div>
        </div>
    </div>
    
    <script>
        // Handle unsave button clicks
        document.querySelectorAll('.btn-unsave').forEach(btn => {
            btn.addEventListener('click', function() {
                if (!confirm('Are you sure you want to remove this project from your saved list?')) {
                    return;
                }
                
                const projectId = this.dataset.projectId;
                const card = this.closest('.project-card');
                const button = this;
                
                // Disable button during request
                button.disabled = true;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Removing...';
                
                fetch('app/api/unsave_project.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'project_id=' + projectId
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Fade out and remove
                        card.style.transition = 'opacity 0.3s, transform 0.3s';
                        card.style.opacity = '0';
                        card.style.transform = 'translateX(-20px)';
                        
                        setTimeout(() => {
                            card.remove();
                            
                            // Reload if no projects left
                            if (document.querySelectorAll('.project-card').length === 0) {
                                location.reload();
                            }
                        }, 300);
                    } else {
                        alert('Error: ' + data.message);
                        button.disabled = false;
                        button.innerHTML = '<i class="fas fa-trash-alt"></i> Remove from Saved';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Failed to remove project. Please try again.');
                    button.disabled = false;
                    button.innerHTML = '<i class="fas fa-trash-alt"></i> Remove from Saved';
                });
            });
        });

        // Generate Proposal
        function generateProposal(projectId, projectTitle, regenerate = false) {
            const modal = document.getElementById('proposalModal');
            const modalBody = document.getElementById('modalBody');
            
            modal.classList.add('active');
            modalBody.innerHTML = '<div class="loading"><div class="spinner"></div><p>AI is crafting your proposal...</p></div>';
            
            const url = 'ai/generate_test.php?project_id=' + projectId + (regenerate ? '&regenerate=1' : '');
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        modalBody.innerHTML = `
                            <h3 style="margin-bottom: 15px;">For: ${escapeHtml(projectTitle)}</h3>
                            <div class="proposal-text">${escapeHtml(data.proposal)}</div>
                            <div style="display: flex; gap: 10px;">
                                <button class="copy-btn" onclick="copyProposal(this)">📋 Copy to Clipboard</button>
                                <button class="copy-btn" style="background: #f59e0b;" onclick="generateProposal(${projectId}, '${escapeHtml(projectTitle).replace(/'/g, "\\'")}', true)">🔄 Regenerate</button>
                            </div>
                        `;
                    } else {
                        modalBody.innerHTML = `
                            <div class="error-message"><strong>Error:</strong> ${escapeHtml(data.error)}</div>
                            <button class="copy-btn" onclick="closeModal()">Close</button>
                        `;
                    }
                })
                .catch(error => {
                    modalBody.innerHTML = `
                        <div class="error-message"><strong>Error:</strong> Failed to generate proposal.</div>
                        <button class="copy-btn" onclick="closeModal()">Close</button>
                    `;
                });
        }

        function closeModal() {
            document.getElementById('proposalModal').classList.remove('active');
        }

        function copyProposal(button) {
            const proposalText = document.querySelector('.proposal-text').textContent;
            navigator.clipboard.writeText(proposalText).then(() => {
                button.textContent = '✓ Copied!';
                button.classList.add('copied');
                setTimeout(() => {
                    button.textContent = '📋 Copy to Clipboard';
                    button.classList.remove('copied');
                }, 2000);
            });
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        document.getElementById('proposalModal').addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });
    </script>
</body>
</html>